package com.yangye.pigenerator.util;

import cn.hutool.core.io.FileUtil;
import cn.hutool.core.util.RandomUtil;
import com.yangye.pigenerator.model.GenConfig;
import org.dom4j.Document;
import org.dom4j.Element;
import org.dom4j.io.OutputFormat;
import org.dom4j.io.SAXReader;
import org.dom4j.io.XMLWriter;

import java.io.File;
import java.io.FileInputStream;
import java.io.FileOutputStream;
import java.util.List;

/**
 * @author yangye
 * @date 2020/03/17
 */
public class XMLUtil {

	public static final String BASE_PATH = System.getProperty("user.dir") + "\\src\\main\\resources\\";

	/**
	 * 新建mybatis-generator配置文件
	 * @return
	 * @throws Exception
	 */
	public static File touchMbgFile(String moduleName, List<GenConfig> configs) throws Exception {
		SAXReader saxReader = new SAXReader();
		Document document = saxReader.read(new FileInputStream(new File(BASE_PATH + "mybatis-generator.xml")));
		Element rootElement = document.getRootElement();
		Element context = rootElement.element("context");
		context.element("javaModelGenerator").addAttribute("targetPackage", "com.yangye." + moduleName + ".domain");
		context.element("javaClientGenerator").addAttribute("targetPackage", "com.yangye." + moduleName + ".dao");
		for (GenConfig config : configs) {
			context.addElement("table").addAttribute("tableName", config.getTableName()).addAttribute("domainObjectName", config.getClassName());
		}
		OutputFormat format = OutputFormat.createPrettyPrint();
		format.setEncoding("utf-8");
		File mbgXmlFile = FileUtil.touch(getMBGXmlPath());
		FileOutputStream outputStream = new FileOutputStream(mbgXmlFile);
		XMLWriter writer = new XMLWriter(outputStream, format);
		writer.write(document);
		writer.close();
		return mbgXmlFile;
	}


	private static String getMBGXmlPath() {
		return BASE_PATH + "mybatis-generator-" + RandomUtil.randomNumbers(4) + ".xml";
	}
}
